package targetToOffer.tenthDay;

/**
 * @author Godc
 * @description
 */
public class TreeToDoublyList {
    private Node root;

    public static void main(String[] args) {
        TreeToDoublyListSolution s = new TreeToDoublyListSolution();
        Node root = new Node(4);
        Node root1 = new Node(2);
        Node root2 = new Node(5);
        Node root3 = new Node(1);
        Node root4 = new Node(3);
        root.left = root1;
        root.right = root2;
        root1.left = root3;
        root1.right = root4;
        s.dfs(root);
    }
}
class TreeToDoublyListSolution {
    Node pre,head;
    /**
     * 线索化二叉树
     * @param root
     * @return
     */
    public Node treeToDoublyList(Node root) {
        if(root==null) return null;
        dfs(root);
        head.left = pre;
        pre.right = head;
        return head;
    }
    public void dfs(Node cur){
        if(cur==null) return;
        // 先处理左子树
        dfs(cur.left);
        if(pre!=null) pre.right = cur;
        else head = cur;
        cur.left = pre;
        pre = cur;
        dfs(cur.right);
    }
}
class Node {
    public int val;
    public Node left;
    public Node right;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val,Node _left,Node _right) {
        val = _val;
        left = _left;
        right = _right;
    }
};